from odoo import api, fields, models, _
from odoo.exceptions import UserError
import requests


class PlanMaterialWizard(models.TransientModel):
    _inherit = 'plan.material.requirement.wizard'

    # def action_plan_material_requirement(self):
    #     res = super().action_plan_material_requirement()
    #     try:
    #         mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')]).s_value  # 表示开启了MES系统传输
    #         url = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.updateImsData')]).s_value
    #         # 这里执行上传 产品, 销售订单 + 工单 到 MES
    #         if mes_enabled:
    #             # 获取销售单
    #             sale_ids = self.sale_order_line.order_id
    #             for sale in sale_ids:
    #                 sale.with_delay(description='同步工单',priority=2).post_mes_async(url)
    #             # 研发单
    #             dev_order_ids = self.development_ids.mapped('order_id') if self.development_ids.mapped('order_id') else []
    #             # print(dev_order_ids)
    #             for dev in dev_order_ids:
    #                 dev.with_delay(description='同步研发单', priority=2).post_mes_async()
    #     except Exception as e:
    #         self.env['api.records'].create({
    #             'api_route': url,
    #             'result_json': e,
    #             'state': 'fail'
    #         })
    #     return res

    def action_plan_material_requirement_02(self, order_ids=[]):
        """5.26上线测试代码"""
        # res = super().action_plan_material_requirement()
        if not order_ids: return
        try:
            url = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.updateImsData')]).s_value
            # 这里执行上传 产品, 销售订单 + 工单 到 MES
            sale_ids = self.env['sale.order'].browse(order_ids)
            for sale in sale_ids:
                # 销售单上传, 异步调用
                sale.with_delay().post_mes_async(url)
        except Exception as e:
            self.env['api.records'].create({
                'api_route': url,
                'result_json': e,
                'state': 'fail'
            })
